package com.yaolong.api.modules.opms.service.impl;

import com.yaolong.api.modules.opms.entity.Message;
import com.yaolong.api.modules.opms.entity.OpmsDistressAttach;
import com.yaolong.api.modules.opms.entity.OpmsDistressRelief;
import com.yaolong.api.modules.opms.dao.OpmsDistressReliefDao;
import com.yaolong.api.modules.opms.entity.OpmsNotice;
import com.yaolong.api.modules.opms.service.MessageService;
import com.yaolong.api.modules.opms.service.OpmsDistressAttachService;
import com.yaolong.api.modules.opms.service.OpmsDistressReliefService;
import com.yaolong.api.modules.opms.service.OpmsNoticeService;
import com.yaolong.api.modules.sys.dto.UserInfoDto;
import com.yaolong.api.modules.sys.po.RoleInfo;
import com.yaolong.api.modules.sys.service.ISysUserInfoService;
import com.yaolong.api.modules.utils.CheckRoleUtils;
import com.yaolong.commons.base2.BaseServiceImpl;
import com.yaolong.commons.exceptions.BusinessException;
import com.yaolong.commons.utils.MapperUtils;
import com.yaolong.commons.web.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 困难救助表 服务实现类
 * </p>
 *
 * @author yaolonga
 * @version v1.0.0
 * @since 2023-02-19
 */
@Service
public class OpmsDistressReliefServiceImpl extends BaseServiceImpl<OpmsDistressReliefDao, OpmsDistressRelief> implements OpmsDistressReliefService {

    @Autowired
    private MessageService messageService;

    @Autowired
    private OpmsDistressAttachService opmsDistressAttachService;

    @Autowired
    private ISysUserInfoService iSysUserInfoService;

    @Autowired
    private OpmsNoticeService opmsNoticeService;


    @Value("${filePath}")
    private String filePath;
    @Value("${fileHost}")
    private String fileHost;
    @Override
    public IPage<OpmsDistressRelief> page(int current, int size, OpmsDistressRelief domain) {
        IPage<OpmsDistressRelief> page = new Page<>(current, size);
        //居民用户只查看自己申请的记录
        UserInfoDto userInfoDto = iSysUserInfoService.userInfoByContext();
        List<RoleInfo> roleInfos = MapperUtils.copyList(userInfoDto.getRoles(), RoleInfo.class);
        Long userId = userInfoDto.getUserId();
        boolean flag = CheckRoleUtils.checkRole(roleInfos);
        if (!CheckRoleUtils.checkAdminRole(roleInfos)) {
            //无管理员权限
            if (!flag) {
                //居民用户
                domain.setCreatedBy(userId);
            } else {
                //审核员
                domain.setStatus("审核中");
            }
        }
        return lambdaQuery()
                .like(!ObjectUtils.isEmpty(domain.getType()), OpmsDistressRelief::getType, domain.getType())
                .eq(!ObjectUtils.isEmpty(domain.getStatus()), OpmsDistressRelief::getStatus, domain.getStatus())
                .eq(!ObjectUtils.isEmpty(domain.getCreatedBy()), OpmsDistressRelief::getCreatedBy, domain.getCreatedBy())
                .orderByAsc(OpmsDistressRelief::getDateCreated)
                .page(page).convert(i -> {
                    List<OpmsDistressAttach> list = opmsDistressAttachService.lambdaQuery().eq(OpmsDistressAttach::getDistressReliefId, i.getId()).list();
                    i.setFiles(list);
                    return i;
                });
    }

    @Override
    public List<OpmsDistressRelief> list(OpmsDistressRelief domain) {
        return lambdaQuery()
                .like(!ObjectUtils.isEmpty(domain.getType()), OpmsDistressRelief::getType, domain.getType())
                .eq(!ObjectUtils.isEmpty(domain.getStatus()), OpmsDistressRelief::getStatus, domain.getStatus())
                .list();
    }


    /**
     * 申请求助将发送一条提示消息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean create(OpmsDistressRelief domain) {
        domain.setStatus("审核中");
        super.create(domain);
        //创建消息
        Message message = new Message();
        message.setSenderBy(domain.getCreatedBy());
        message.setSenderByName(domain.getCreatedByName());
        message.setContent(domain.getCreatedByName() + "发起了一条申请");
        message.setReceiverBy(2L);
        message.setReceiverByName("admin");
        message.setIsHandle(false);//0
        message.setTopicId(domain.getId());
        //保存附件
        if (null != domain.getFiles()) {
            //List<OpmsDistressAttach> opmsDistressAttaches = uploadAttach(domain.getFiles());
            List<OpmsDistressAttach> files = domain.getFiles();
            if (!files.isEmpty()) {
                for (OpmsDistressAttach attach : files) {
                    attach.setDistressReliefId(domain.getId());
                }
                opmsDistressAttachService.saveBatch(files);
            }
        }

        return messageService.create(message);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(OpmsDistressRelief domain) {
        if (super.update(domain)) {
            UserInfoDto userInfoDto = iSysUserInfoService.userInfoByContext();
            Message message = new Message();
            message.setSenderBy(userInfoDto.getUserId());
            message.setSenderByName(userInfoDto.getUsername());
            message.setContent(userInfoDto.getUsername() + "审核了你发起的申请");
            message.setReceiverBy(domain.getCreatedBy());
            message.setReceiverByName(domain.getCreatedByName());
            message.setIsHandle(true);
            message.setTopicId(domain.getId());
            if ("已通过".equals(domain.getStatus())) {
                OpmsNotice opmsNotice = new OpmsNotice();
                opmsNotice.setCreatedBy(domain.getCreatedBy());
                opmsNotice.setContent(userInfoDto.getUsername() + "同意了你发起的申请");
                opmsNotice.setTitile("困难申请");
                opmsNotice.setType("其他公告");
                opmsNotice.setSendId(domain.getCreatedBy());
                opmsNoticeService.create(opmsNotice);
            }
            return messageService.create(message);
        } else {
            return false;
        }
    }

    @Override
    public boolean uploadFile(List<MultipartFile> files) {
        try {
            //判断文件夹是否存在，不存在时，创建文件夹
            File directoryFile = new File(filePath);
            if (!directoryFile.exists()) {
                //创建多个文件夹
                directoryFile.mkdirs();
            }

            if (files.isEmpty()) {
                throw new BusinessException("上传文件不能为空！");
            }
            UserInfoDto userInfoDto = iSysUserInfoService.userInfoByContext();
            for (MultipartFile file : files) {
                //原始文件名(不使用原始的文件名防止文件覆盖)
                String fileName = file.getOriginalFilename();
                if (null == fileName) {
                    throw new BusinessException("上传文件名不能为空！");
                }
                if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
                    throw new BusinessException("上传文件名词存在非法字符！");
                }
                //获取文件名的后缀
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                //使用UUID重新生成文件名，防止文件名重复造成图片覆盖
                String fileNameEnd = UUID.randomUUID().toString() + suffix;
                //上传到本地
                file.transferTo(new File(filePath + fileNameEnd));
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
    }

    @Override
    public Map<String,Object> uploadAttach(MultipartFile files) {
        try {
            //判断文件夹是否存在，不存在时，创建文件夹
            File directoryFile = new File(filePath);
            if (!directoryFile.exists()) {
                //创建多个文件夹
                directoryFile.mkdirs();
            }

            if (files.isEmpty()) {
                throw new BusinessException("上传文件不能为空！");
            }
            UserInfoDto userInfoDto = iSysUserInfoService.userInfoByContext();
            //原始文件名(不使用原始的文件名防止文件覆盖)
            String fileName = files.getOriginalFilename();
            if (null == fileName) {
                throw new BusinessException("上传文件名不能为空！");
            }
            //获取文件名的后缀
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String name = fileName.substring(0,fileName.lastIndexOf("."));
            //使用UUID重新生成文件名，防止文件名重复造成图片覆盖
            String fileNameEnd = name + UUID.randomUUID().toString() + suffix;
            //上传到本地
            files.transferTo(new File(filePath + fileNameEnd));

            HashMap<String, Object> map = new HashMap<>();
            map.put("url",fileHost+ "/" + fileNameEnd);
            map.put("name",fileName);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
    }
}
